package com.javapda.c328r.util;

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.PortInUseException;

import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class PortAvailabilityUtil {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println(getAvailableSerialPorts());

	}

	/**
	 * @return A HashSet containing the CommPortIdentifier for all serial ports
	 *         that are not currently being used.
	 */
	public static Set getAvailableSerialPorts() {
		Set h = new HashSet();
		Enumeration thePorts = CommPortIdentifier.getPortIdentifiers();
		while (thePorts.hasMoreElements()) {
			CommPortIdentifier com = (CommPortIdentifier) thePorts
							.nextElement();

			switch (com.getPortType()) {
			case CommPortIdentifier.PORT_SERIAL:
				try {
					CommPort thePort = com.open("CommUtil", 50);
					System.out
									.println("Serial Port Name: "
													+ thePort.getName());
					thePort.close();
					h.add(com);
				} catch (PortInUseException e) {
					System.out.println("Port, " + com.getName()
									+ ", is in use.");
				} catch (Exception e) {
					System.err.println("Failed to open port " + com.getName());
					e.printStackTrace();
				}
				break;
			default:
				System.out.println("Some Other time " + com.getPortType());
			}
		}
		return h;
	}
	public static Map getAvailableSerialPortMap() {
		Map map = new TreeMap();
		Set set = getAvailableSerialPorts();
		for (Iterator iterator = set.iterator(); iterator.hasNext();) {
			CommPortIdentifier port = (CommPortIdentifier) iterator.next();
			map.put(port.getName(), port);
		}
		return map;
	}

	public static void listPorts() {
		java.util.Enumeration portEnum = CommPortIdentifier
						.getPortIdentifiers();
		while (portEnum.hasMoreElements()) {
			CommPortIdentifier portIdentifier = (CommPortIdentifier) portEnum
							.nextElement();
			System.out.println(portIdentifier.getName() + " - "
							+ PortTypeUtil.getPortTypeName(portIdentifier.getPortType()));
		}
	}


}
